package com.cdy.jxc_project.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cdy.jxc_project.domain.TAdmin;
import com.cdy.jxc_project.domain.TAdminRole;
import com.cdy.jxc_project.domain.TMenuRole;
import com.cdy.jxc_project.domain.vo.TAdminLoginVo;
import com.cdy.jxc_project.json.R;
import com.cdy.jxc_project.mapper.TAdminMapper;
import com.cdy.jxc_project.mapper.TAdminRoleMapper;
import com.cdy.jxc_project.service.TAdminService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/*
 * @Project:jxc_project
 * @Author:cdy(缘生)
 * @Motto:放下杂念,只为迎接明天更好的自己
 * @Date:2023/4/20 14:07
 * */
@Service
@Transactional
public class TAdminServiceImpl extends ServiceImpl<TAdminMapper, TAdmin> implements TAdminService {

    @Resource
    private TAdminRoleMapper tAdminRoleMapper;
    @Resource
    private TAdminMapper tAdminMapper;

    @Override
    public List<TAdmin> queryAll() {
        return tAdminMapper.selectList(null);
    }

    @Override
    public int deleteTAdmin(Integer id) {
        return tAdminMapper.deleteById(id);
    }

    @Override
    public int insertTAdmin(TAdmin tAdmin) {
        return tAdminMapper.insert(tAdmin);
    }

    @Override
    public int updateTAdmin(TAdmin tAdmin) {
        return tAdminMapper.updateById(tAdmin);
    }

    @Override
    public R authToAdmin(Integer aid, List<Integer> rids) {
        // 删除原有权限
        QueryWrapper wrapper = new QueryWrapper();
        wrapper.eq("admin_id", aid);
        tAdminRoleMapper.delete(wrapper);
        if (CollectionUtils.isEmpty(rids)) {
            return R.error();
        } else {
            List<TAdminRole> list = new ArrayList<>();
            for (Integer rid : rids) {
                TAdminRole adminRole = new TAdminRole();
                adminRole.setAdminId(aid);
                adminRole.setRid(rid);
                list.add(adminRole);
            }

            // 重新赋予权限
            Integer result = tAdminRoleMapper.insertBatch(list);
            return R.ok();
        }

    }

    @Override
    public List<Integer> getAdminRole(Integer id) {

        return tAdminRoleMapper.getAdminRole(id);
    }
}
